package com.yss.common.datascope.aspect;

import java.util.ArrayList;
import java.util.List;

import com.yss.common.core.constant.SecurityConstants;
import com.yss.common.core.domain.YssResponse;
import com.yss.system.api.RemoteDeptService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.yss.common.core.utils.StringUtils;
import com.yss.common.core.web.domain.BaseEntity;
import com.yss.common.datascope.annotation.DataScope;
import com.yss.common.security.utils.SecurityUtils;
import com.yss.system.api.domain.SysRole;
import com.yss.system.api.domain.SysUser;
import com.yss.system.api.model.LoginUser;

/**
 * 数据过滤处理
 */
@Aspect
@Component
public class DataScopeAspect {
    @Autowired
    private RemoteDeptService remoteDeptService;
    /**
     * 全部数据权限
     */
    public static final String DATA_SCOPE_ALL = "1";

    /**
     * 自定数据权限
     */
    public static final String DATA_SCOPE_CUSTOM = "2";

    /**
     * 部门数据权限
     */
    public static final String DATA_SCOPE_DEPT = "3";

    /**
     * 部门及以下数据权限
     */
    public static final String DATA_SCOPE_DEPT_AND_CHILD = "4";

    /**
     * 仅本人数据权限
     */
    public static final String DATA_SCOPE_SELF = "5";

    /**
     * 数据权限过滤关键字
     */
    public static final String DATA_SCOPE = "dataScope";

    @Before("@annotation(controllerDataScope)")
    public void doBefore(JoinPoint point, DataScope controllerDataScope) throws Throwable {
        clearDataScope(point);
        handleDataScope(point, controllerDataScope);
    }

    protected void handleDataScope(final JoinPoint joinPoint, DataScope controllerDataScope) {
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (StringUtils.isNull(loginUser)) {
            return;
        }
        SysUser currentUser = loginUser.getSysUser();
        // 如果是超级管理员，则不过滤数据
        if (StringUtils.isNull(currentUser) || currentUser.isAdmin()) {
            return;
        }
        this.dataScopeFilter(joinPoint, currentUser);
    }

    /**
     * 数据范围过滤
     *
     * @param joinPoint 切点
     * @param user      用户
     */
    public void dataScopeFilter(JoinPoint joinPoint, SysUser user) {
        List<String> conditions = new ArrayList<String>();
        List<String> deptIds = new ArrayList<>();
        for (SysRole role : user.getRoles()) {
            String dataScope = role.getDataScope();
            if (!DATA_SCOPE_CUSTOM.equals(dataScope) && conditions.contains(dataScope)) {
                continue;
            }
            if (DATA_SCOPE_ALL.equals(dataScope)) {
                deptIds.clear();
                break;
            } else if (DATA_SCOPE_CUSTOM.equals(dataScope)) {
                YssResponse<List<String>> response = remoteDeptService.getRoleDeptIds(role, SecurityConstants.INNER);
                List<String> list = response.getData();
                if (StringUtils.isNotEmpty(list)) {
                    deptIds.addAll(list);
                }
            } else if (DATA_SCOPE_DEPT.equals(dataScope)) {
                deptIds.add(user.getDeptId());
            } else if (DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope)) {
                YssResponse<List<String>> response = remoteDeptService.getUserDeptIds(user, SecurityConstants.INNER);
                List<String> list = response.getData();
                if (StringUtils.isNotEmpty(list)) {
                    deptIds.addAll(list);
                }
            } /*else if (DATA_SCOPE_SELF.equals(dataScope)) {
                if (StringUtils.isNotBlank(userAlias)) {
                    sqlString.append(StringUtils.format(" OR {}.ID = {} ", userAlias, user.getId()));
                } else {
                    // 数据权限为仅本人且没有userAlias别名不查询任何数据
                    sqlString.append(StringUtils.format(" OR {}.ID = 0 ", deptAlias));
                }
            }*/
            conditions.add(dataScope);
        }

        if (StringUtils.isNotEmpty(deptIds)) {
            Object params = joinPoint.getArgs()[0];
            if (StringUtils.isNotNull(params) && params instanceof BaseEntity) {
                BaseEntity baseEntity = (BaseEntity) params;
                baseEntity.getParams().put(DATA_SCOPE, deptIds);
            }
        }
    }

    /**
     * 拼接权限sql前先清空params.dataScope参数防止注入
     */
    private void clearDataScope(final JoinPoint joinPoint) {
        Object params = joinPoint.getArgs()[0];
        if (StringUtils.isNotNull(params) && params instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) params;
            baseEntity.getParams().put(DATA_SCOPE, null);
        }
    }
}
